package cn.chinaflame.pagodas.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.chinaflame.pagodas.annotation.ApiDoc;
import cn.chinaflame.pagodas.entity.PaBadLights;
import cn.chinaflame.pagodas.entity.PaEmailLog;
import cn.chinaflame.pagodas.service.PaBadLightsService;
import cn.chinaflame.pagodas.service.PaEmailLogService;
import cn.chinaflame.pagodas.utils.email.Email;
import cn.chinaflame.pagodas.utils.email.EmailService;
import cn.chinaflame.pagodas.utils.stl.DateUtils;

@RestController
@Transactional(rollbackFor = Exception.class)
@RequestMapping(value = "/openapi/v1/pagodas/email/")
public class OpenEmailAPI {

    private static final Logger log = LoggerFactory.getLogger(OpenEmailAPI.class);
    
	@Autowired
    private Email email;
	
	@Autowired
	private PaEmailLogService paEmailLogService;
	
    @Autowired
    private EmailService emailService;
  
    @Autowired
    private PaBadLightsService paBadLightsService;
    
    /**
     * 
     * @param request
     * @param response
     * @return
     */
    @PostMapping("sendEmail")
    @ApiDoc(value = Email.class, result = Email.class)
    public String sendEmail(HttpServletRequest request,HttpServletResponse response) {
    	String date = DateUtils.getYesterday1();
    	List<PaBadLights> list = paBadLightsService.findByCreatetime(date); 
    	
    	
    	StringBuffer content = new StringBuffer();
    	content.append("各位好：\r\n");
    	content.append("附件Excel内容为寻灯或安灯异常的灯号，烦请予以查收并检测维修.\r\n");
    	content.append("请务必保持现场的灯能正常使用，感谢贵单位的辛苦配合.\r\n");
    	content.append("上海炎武金服祝您工作顺利，生活愉快.\r\n");
    	email.setBody(content.toString());
    	log.info("email="+email.toString());
    	boolean result = emailService.sendEmail(email);
    	PaEmailLog log = new PaEmailLog();
    	log.setReceiver(email.getSendTo());
    	log.setSubject(email.getTopic());
    	log.setContent(email.getBody());
    	log.setCopyto(email.getCopyTo());
    	log.setResult(result?"发送成功！":"发送失败！");
    	paEmailLogService. addEmail(log);
    	return "";
    }
}
